package com.thinkgem.jeesite.modules.oa.web;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.act.entity.Act;
import com.thinkgem.jeesite.modules.act.service.ActTaskService;
import com.thinkgem.jeesite.modules.act.utils.ProcessDefUtils;
import com.thinkgem.jeesite.modules.form.entity.Component;
import com.thinkgem.jeesite.modules.form.entity.OaFormMaster;
import com.thinkgem.jeesite.modules.form.service.OaFormMasterService;
import com.thinkgem.jeesite.modules.form.util.ComponentUtils;
import com.thinkgem.jeesite.modules.oa.entity.FlowData;
import com.thinkgem.jeesite.modules.oa.entity.PersonSigns;
import com.thinkgem.jeesite.modules.oa.service.FlowService;
import com.thinkgem.jeesite.modules.oa.service.PersonSignsService;
import com.thinkgem.jeesite.modules.oa.service.TargetHospitalService;
import com.thinkgem.jeesite.modules.oa.units.CommonUtils;
import com.thinkgem.jeesite.modules.oa.units.FreemarkerUtils;
import com.thinkgem.jeesite.modules.sys.dao.RoleDao;
import com.thinkgem.jeesite.modules.sys.dao.UserDao;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.NoticeUnits;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.table.entity.OaPersonDefineTable;
import com.thinkgem.jeesite.modules.table.entity.OaPersonDefineTableColumn;
import com.thinkgem.jeesite.modules.table.service.OaPersonDefineTableService;
import com.thinkgem.jeesite.modules.test.testmsm.SmsModule;
import eu.bitwalker.useragentutils.DeviceType;
import eu.bitwalker.useragentutils.UserAgent;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 流程Controller
 *
 * @author lgx
 * @version 2016-12-12
 */
@Controller
@RequestMapping(value = "${adminPath}/oa/flow")
public class FlowController extends BaseController {


    @Autowired
    private ActTaskService actTaskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private FlowService flowService;
    @Autowired
    private OaFormMasterService oaFormMasterService;
    @Autowired
    private OaPersonDefineTableService oaPersonDefineTableService;

    @Autowired
    private PersonSignsService personSignsService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private TargetHospitalService targetHospitalService;
    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @RequestMapping(value = "form")
    public void form(FlowData flow, Model model, HttpServletResponse response, String flag) {
        OaFormMaster form = oaFormMasterService.findByNo(flow.getFormNo(), null);
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("tableName", form.getTableName());
        paramMap.put("procInsId", flow.getAct().getProcInsId());
        paramMap.put("id", flow.getId());
        if (StringUtils.isNotEmpty(flag)) {
            paramMap.put("BZ", flag);
        }
        flow.setTableName(form.getTableName());

        String view;
        if (StringUtils.isNotBlank(flow.getShowType())) {
            view = flow.getShowType();
            flow.setDatas(flowService.getOneInfo(paramMap));
        } else {
            view = "flowForm";
            // 查看审批申请单
            if (StringUtils.isNotBlank(flow.getId())) {
                // 环节编号
                String taskDefKey = flow.getAct().getTaskDefKey();
                // 查看
                if (flow.getAct().isFinishTask()) {
                    view = "flowView";
                }
                // 修改环节
                else if ("modify".equals(taskDefKey) || (taskDefKey).startsWith("edit")) {
                    view = "flowForm";
                }
                // 审核
                else if (taskDefKey.startsWith("audit") || "apply_end".equals(taskDefKey) || (taskDefKey).startsWith("apply_execute") || (taskDefKey).startsWith("apply_cs") ) {
                    view = "flowAudit";
                }
                flow.setDatas(flowService.getOneInfo(paramMap));
            }
        }

        Component c = ComponentUtils.getComponent(view);
        initComponent(form, view, StringUtils.isBlank(flow.getId()));
        String initJs = "";
        if (StringUtils.isNotBlank(flow.getId()) && "flowForm".equals(view)) {
            initJs = getInitJs(flow.getDatas(), form.getTableName());
        }
        String html = c.getContent().replace("$flowTableInfo$", form.getContent()).replace("$initJs$", initJs);
        html = html.replace("<td", "<td ");//nowrap='nowrap'
        flow.setShowType(view);
        if (StringUtils.isNoneBlank(flag)) {
            flow.getAct().setBZ(flag);
        }
        try {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print(FreemarkerUtils.process(html, toMap(flow)));
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "saveContractFile")
    public void saveContractFile(@RequestParam("file") MultipartFile file, String name, String signName, String id,
                                 RedirectAttributes redirectAttributes, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        String url = flowService.saveContractFile(file, name, signName, id, request);
        String res = "{error:'" + url + "'}";
        System.out.println(res);
        response.getWriter().write(res);
    }

    @RequestMapping(value = "save")
    public String save(String startAct, String endAct, FlowData flowData, HttpServletRequest request, RedirectAttributes redirectAttributes, HttpServletResponse response) throws Exception {
        String message = null;
        Map data = request.getParameterMap();
        FlowData flowParam = new FlowData();
        String html = "";
        if (data != null) {
            data = CommonUtils.mapConvert(data);
            String[] filterName = {"tableName", "act.taskId", "act.taskName", "act.taskDefKey",
                    "act.procInsId", "act.flag", "id", ""};
            data = CommonUtils.attributeMapFilter(data, filterName);
            String procDefId = flowData.getAct().getProcDefId();
            flowData.setFlowFlag(procDefId.substring(0, procDefId.indexOf(":")));
            flowData.setDatas(data);
            PersonSigns personSigns = personSignsService.getLoginId(UserUtils.getUser().getId());
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            String date = df.format(new Date());// new Date()为获取当前系统时间
            if (personSigns != null) {
                String url = "<img style=\"width:90px; height:60px\" src=\"" + personSigns.getSignUrl() + "\"/>";
                if (StringUtils.isEmpty(flowData.getAct().getComment()) || flowData.getAct().getComment() == "") {
                    flowData.getAct().setComment(date + "<br>" + url);
                }
            }
            try {
                try {
                    String proInsId = flowService.saveFlow(flowData);
                    if (StringUtils.isNotEmpty(proInsId) || StringUtils.isNotEmpty(flowData.getAct().getProcInsId())) {
                        if (StringUtils.isNotEmpty(flowData.getAct().getProcInsId())) {
                            proInsId = flowData.getAct().getProcInsId();
                        }
                        List<Task> tasks = taskService.createTaskQuery().processInstanceId(proInsId).list();
                        String assigneeName = tasks.get(0).getAssignee();   //下一步审批人的登录名
                        User user = new User();
                        if (StringUtils.isNotEmpty(assigneeName)) {
                            user = systemService.getUserByLoginName(assigneeName);
                        }
                        String tableName = flowData.getTableName();
                        OaPersonDefineTable table = oaPersonDefineTableService.findByTableName(tableName, null);
                        String tableComment = table.getTableComment();
                        if (tableComment.equals("预借款申请单")) {
                            tableComment = "预借款" + " " + "申请单";
                        }
                        ProcessDefinitionEntity def = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(tasks.get(0).getProcessDefinitionId());
                        List<ActivityImpl> activitiList = def.getActivities(); //rs是指RepositoryService的实例
                        String excId = tasks.get(0).getExecutionId();
                        ExecutionEntity execution = (ExecutionEntity) runtimeService.createExecutionQuery().executionId(excId).singleResult();
                        String activitiId = execution.getActivityId();

                        for (ActivityImpl activityImpl : activitiList) {
                            String id = activityImpl.getId();
                            if (activitiId.equals(id)) {
                                message = "【<span>" + tableComment + "</span>】提交成功<br>下一步【" + activityImpl.getProperty("name") + "】";
                                if (StringUtils.isNotEmpty(user.getName())) {
                                    message = message + "审批人是：<span>" + user.getName() + "</span>";
                                    //发送待办流程短信
//                                           SmsModule.flowWork(user.getMobile(),user.getName(),UserUtils.getUser().getName(),tableComment);
                                    //  System.out.println(user.getMobile()+ user.getName() + "您好，您有待办流程：" + UserUtils.getUser().getName() + "发起了" + tableComment + "，请您尽快处理。");
                                    //  return SendSms.sendSmsO(Mobile, name1 + "您好，您有待办流程：" + name2 + "发起了" + content + "，请您尽快处理。");
                                    Act act = flowData.getAct();
                                    List<Act> histoicFlowList = actTaskService.histoicFlowList(act.getProcInsId(), startAct, endAct);
                                    if (histoicFlowList.size() == 0) {
                                        SmsModule.flowWork(user.getMobile(), user.getName(), UserUtils.getUser().getName(), tableComment);
//                                        System.out.println(user.getMobile()+ user.getName() + "您好，您有待办流程：" + UserUtils.getUser().getName() + "发起了" + tableComment + "，请您尽快处理。");
                                    } else {
                                        String name = histoicFlowList.get(0).getAssigneeName();
                                        String procInsId = act.getProcInsId();
                                        // 获取代办流程候选人列表
                                        List<Task> tasks1 = taskService.createTaskQuery().processInstanceId(procInsId).list();
                                        String assigneeName1 = tasks1.get(0).getAssignee();   //下一步审批人的登录名
                                        String tableName1 = flowData.getTableName();
                                        OaPersonDefineTable table1 = oaPersonDefineTableService.findByTableName(tableName1, null);
                                        String tableComment1 = table1.getTableComment();
                                        if (tableComment1.equals("预借款申请单")) {
                                            tableComment1 = "预借款" + " " + "申请单";
                                        }
                                        if (StringUtils.isBlank(assigneeName1)) {
                                            List<IdentityLink> IdentityLinks = taskService.getIdentityLinksForTask(tasks.get(0).getId());
                                            if (IdentityLinks.size() == 1) {
                                                for (IdentityLink il : IdentityLinks) {
                                                    String id1 = il.getUserId();
                                                    User u = new User();
                                                    u.setLoginName(id);
                                                    User user1 = userDao.getByLoginName(u);
                                                    String name1 = user.getName();
                                                    String Mobile = user.getMobile();
                                                    SmsModule.flowWork(Mobile, name1, name, tableComment1);
//                                                    System.out.println( name1 + "您好，您有待办流程：" + name + "发起了" + tableComment + "，请您尽快处理。");
                                                }
                                            } else {
                                                String str = "";
                                                String str1 = "";
                                                String Mobile = "";
                                                List<String> Mobiles = new ArrayList<>();
                                                for (IdentityLink il : IdentityLinks) {
                                                    String id1 = il.getUserId();
                                                    User u = new User();
                                                    u.setLoginName(id);
                                                    User user1 = userDao.getByLoginName(u);
                                                    String name1 = user.getName();
                                                    str += name1 + "、";
                                                    str1 = str.substring(0, str.length() - 1);
                                                    Mobile = user.getMobile();
                                                    Mobiles.add(Mobile);
                                                }
                                                for (int i = 0; i < Mobiles.size(); i++) {
                                                    SmsModule.flowWork(Mobiles.get(i), str1, name, tableComment1);
                                                    System.out.println(str1 + "您好，您有待办流程：" + name + "发起了" + tableComment + "，请您尽快处理。");
                                                }
                                            }
                                        } else {
                                            String name1 = null;
                                            String Mobile = null;
                                            for (int i = 1; i < histoicFlowList.size(); i++) {
                                                name1 = histoicFlowList.get(i).getTaskName();
                                                Mobile = histoicFlowList.get(i).getFlag();
                                            }
                                            SmsModule.flowWork(Mobile, name1, name, tableComment1);
                                        }
                                    }
                                }
                                response.setContentType("text/html;charset=utf-8");
                                List<Object[]> processList = ProcessDefUtils.processList(null);
                                //默认选择第一个流程
                                StringBuilder selfFlowHTML = new StringBuilder();
                                for (Object[] objs : processList) {
                                    ProcessDefinition process = (ProcessDefinition) objs[0];
                                    selfFlowHTML.append("<option " + (procDefId.equals(process.getId()) ? "selected=\"selected\"" : "")
                                            + " value=\"" + process.getId() + "\">" + process.getName() + "</option>");
                                }
                                String formKey = actTaskService.getFormKey(procDefId, null);
                                if (StringUtils.isNotBlank(formKey) && !"/404".equals(formKey)) {
                                    OaFormMaster form = oaFormMasterService.findByNo(formKey, null);
                                    if (form != null) {
                                        String tableName1 = form.getTableName();
                                        flowParam.setTableName(tableName1);
                                        flowParam.setFormNo(form.getFormNo());
                                        OaPersonDefineTable table1 = oaPersonDefineTableService.findByTableName(tableName1, null);
                                        OaPersonDefineTableColumn param = new OaPersonDefineTableColumn();
                                        param.setIsShow("1");
                                        param.setTable(table1);
                                        List<OaPersonDefineTableColumn> columns = oaPersonDefineTableService.findColumnList(param);
                                        StringBuilder theadHTML = new StringBuilder();
                                        StringBuilder tbodyHTML = new StringBuilder();
                                        for (OaPersonDefineTableColumn column : columns) {
                                            theadHTML.append("<th>" + column.getColumnComment() + "</th>");
                                            tbodyHTML.append("<td>${item." + column.getColumnName() + "}</td>");
                                        }

                                        Map<String, String> paramMap = new HashMap<>();
                                        paramMap.put("tableName", form.getTableName());
                                        paramMap.put("procDefId", procDefId);
                                        User user1 = UserUtils.getUser();
                                        if (!user1.isAdmin()) {
                                            paramMap.put("createBy", user1.getId());
                                        }
                                        Page<Map<String, Object>> page = flowService.getPageFlowInfo(new Page<FlowData>(request, response), paramMap);
                                        List<Map<String, Object>> flowInfo = page.getList();

                                        flowParam.setDatas(new HashMap<String, Object>());
                                        flowParam.getDatas().put("flowInfo", flowInfo);
                                        flowParam.getDatas().put("page", page);

                                        Component c = ComponentUtils.getComponent("myFlow");
                                        html = c.getContent().replace("$selfFlowHTML$", selfFlowHTML.toString())
                                                .replace("$tbodyHTML$", tbodyHTML.toString())
                                                .replace("$theadHTML$", theadHTML.toString());
                                    }
                                    flowParam.getDatas().put("message", message);
                                }
                                break;
                            }
                        }
                    } else {
                        message = "业务提交成功";
                        flowParam.getDatas().put("message", message);
                    }
                    response.getWriter().print(FreemarkerUtils.process(html, toMap(flowParam)));
                    response.getWriter().flush();
                    return null;
                } catch (Exception e) {
                    e.printStackTrace();
                    message = "业务提交失败";
                    flowParam.getDatas().put("message", message);
                }
            } catch (Exception e) {
                e.printStackTrace();
                message = e.getMessage();
            }
        }
        addMessage(redirectAttributes, message);
        return "redirect:" + adminPath + "/oa/flow/myFlow";
    }


    @RequestMapping(value = "saveAudit")
    public String saveAudit(String startAct, String endAct, FlowData flowData, Model model, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        if (StringUtils.isEmpty(flowData.getAct().getComment()) && StringUtils.equals(flowData.getAct().getTaskDefKey(), "apply_end")) {
            flowData.getAct().setComment("归档");
        }
        String userId = UserUtils.getUser().getLoginName();//ObjectUtils.toString(UserUtils.getUser().getId());
        actTaskService.claim(flowData.getAct().getTaskId(), userId);

        PersonSigns personSigns = personSignsService.getLoginId(UserUtils.getUser().getId());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String date = df.format(new Date());// new Date()为获取当前系统时间

        if (personSigns != null) {
            String url = "<img style=\"width:90px;height:60px;\" src=\"" + personSigns.getSignUrl() + "\"/>";
            if (StringUtils.isEmpty(flowData.getAct().getComment()) || flowData.getAct().getComment() == "") {
                flowData.getAct().setComment(date + "<br>");
            } else {
                flowData.getAct().setComment(flowData.getAct().getComment() + "<br>" + date + "<br>");
            }
            String comment = flowData.getAct().getComment() + url;
            flowData.getAct().setComment(comment);
        } else {
            if (StringUtils.isEmpty(flowData.getAct().getComment()) || flowData.getAct().getComment() == "") {
                flowData.getAct().setComment(date);
            } else {
                flowData.getAct().setComment(flowData.getAct().getComment() + "<br>" + date + "<br>");
            }
            String comment = flowData.getAct().getComment();
            flowData.getAct().setComment(comment);
        }
        String flag = flowService.auditSave(flowData);
        Act act = flowData.getAct();
        List<Act> histoicFlowList = actTaskService.histoicFlowList(act.getProcInsId(), startAct, endAct);
        String name = histoicFlowList.get(0).getAssigneeName();
        String procInsId = act.getProcInsId();
        // 获取代办流程候选人列表
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(procInsId).list();
        if (tasks.size() != 0) {
            String assigneeName = tasks.get(0).getAssignee();   //下一步审批人的登录名
            String tableName = flowData.getTableName();
            OaPersonDefineTable table = oaPersonDefineTableService.findByTableName(tableName, null);
            String tableComment = table.getTableComment();
            if (tableComment.equals("预借款申请单")) {
                tableComment = "预借款" + " " + "申请单";
            }
            if (StringUtils.isBlank(assigneeName)) {
                List<IdentityLink> IdentityLinks = taskService.getIdentityLinksForTask(tasks.get(0).getId());
                if (IdentityLinks.size() == 1) {
                    for (IdentityLink il : IdentityLinks) {
                        String id = il.getUserId();
                        User u = new User();
                        u.setLoginName(id);
                        User user = userDao.getByLoginName(u);
                        String name1 = user.getName();
                        String Mobile = user.getMobile();
                        SmsModule.flowWork(Mobile, name1, name, tableComment);
                        // System.out.println( name1 + "您好，您有待办流程：" + name + "发起了" + tableComment + "，请您尽快处理。");
                    }
                } else {
                    String str = "";
                    String str1 = "";
                    String Mobile = "";
                    List<String> Mobiles = new ArrayList<>();
                    for (IdentityLink il : IdentityLinks) {
                        String id = il.getUserId();
                        User u = new User();
                        u.setLoginName(id);
                        User user = userDao.getByLoginName(u);
                        String name1 = user.getName();
                        str += name1 + "、";
                        str1 = str.substring(0, str.length() - 1);
                        Mobile = user.getMobile();
                        Mobiles.add(Mobile);
                    }
                    for (int i = 0; i < Mobiles.size(); i++) {
                        SmsModule.flowWork(Mobiles.get(i), str1, name, tableComment);
                        // System.out.println( str1 + "您好，您有待办流程：" + name + "发起了" + tableComment + "，请您尽快处理。");
                    }
                }
            } else {
                String name1 = null;
                String Mobile = null;
                for (int i = 1; i < histoicFlowList.size(); i++) {
                    name1 = histoicFlowList.get(i).getTaskName();
                    Mobile = histoicFlowList.get(i).getFlag();
                }
                SmsModule.flowWork(Mobile, name1, name, tableComment);
            }
        }
        if (StringUtils.equalsIgnoreCase(flag, "yes")) {
            addMessage(redirectAttributes, "审批已通过");
        }
        if (StringUtils.equalsIgnoreCase(flag, "no")) {
            addMessage(redirectAttributes, "审批已驳回，等待申请人修改");
        }

        return "redirect:" + adminPath + "/act/task/todo/";
    }


    @RequestMapping(value = "flowList")
    public String FlowList(String procDefId, String category, HttpServletRequest request, HttpServletResponse response,Model model) {
        List<OaPersonDefineTable> list = flowService.flowList();
        Page<OaPersonDefineTable> page = new Page<>();
        page.setList(list);
        model.addAttribute("page",page);
        return "modules/oa/flowList";
    }




    @RequestMapping(value = "myFlow")
    public String myFlow(String procDefId, String category, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        String html = "";
        String cate = null;
        FlowData flowParam = new FlowData();
        List<Role> roles = roleDao.getByRoleName(UserUtils.getUser().getId());//获取当前人员的职位信息
        String companyId = UserUtils.getUser().getCompany().getId();//获取当前人员的单位
        User user1 = userDao.findUserByRoleName(new User());//获取集团管理员的机构id
        for (Role role : roles) {
            if (StringUtils.equalsIgnoreCase(companyId, "1")) {
                category = "";
            } else if (StringUtils.equalsIgnoreCase(role.getName(), "集团管理员") || StringUtils.equalsIgnoreCase(UserUtils.getUser().getCompany().getId(), user1.getCompanyId())
                    || StringUtils.equalsIgnoreCase(role.getName(), "深圳管理员") || StringUtils.equalsIgnoreCase(UserUtils.getUser().getCompany().getId(), user1.getCompanyId()) ) {
                category = "1";
            } else {
                category = "2";
            }//根据人员职位获取栏目类型
        }
        if (StringUtils.isNotEmpty(category)) {
            cate = category;
        }
        List<Object[]> processList = ProcessDefUtils.processList(cate);//保存两个对象，流程定义和流程部署
        //默认选择第一个流程
        if (StringUtils.isBlank(procDefId) && processList.size() > 0) {
            ProcessDefinition process = (ProcessDefinition) processList.get(0)[0];
            procDefId = process.getId();//流程定义id
        }
        //自定义流程HTML
        StringBuilder selfFlowHTML = new StringBuilder();
       /* for (Object[] objs : processList) {
            ProcessDefinition process = (ProcessDefinition) objs[0];
            selfFlowHTML.append("<option " + (procDefId.equals(process.getId()) ? "selected=\"selected\"" : "")
                    + " value=\"" + process.getId() + "\">" + process.getName() + "</option>");
        }*/
        String formKey = actTaskService.getFormKey(procDefId, null);//由流程id获取流程节点KEY
        if (StringUtils.isNotBlank(formKey) && !"/404".equals(formKey)) {
            OaFormMaster form = oaFormMasterService.findByNo(formKey, null);//用表单主键获取表单样式
            if (form != null) {
                String tableName = form.getTableName();
                flowParam.setTableName(tableName);
                flowParam.setFormNo(form.getFormNo());//组装流程数据类
                OaPersonDefineTable table = oaPersonDefineTableService.findByTableName(tableName, null);//由form的table名来获取对应的table
                OaPersonDefineTableColumn param = new OaPersonDefineTableColumn();
                param.setIsShow("1");
                param.setTable(table);
                List<OaPersonDefineTableColumn> columns = oaPersonDefineTableService.findColumnList(param);//获取数据内容
                StringBuilder theadHTML = new StringBuilder();
                StringBuilder tbodyHTML = new StringBuilder();
                for (OaPersonDefineTableColumn column : columns) {
                        theadHTML.append("<th>" + column.getColumnComment() + "</th>");
                        tbodyHTML.append("<td>${item." + column.getColumnName() + "}</td>");
                }
                Map<String, String> paramMap = new HashMap<>();
                paramMap.put("tableName", form.getTableName());
                paramMap.put("procDefId", procDefId);
                User user = UserUtils.getUser();
                String role1 = UserUtils.getRole().get(0).getName();
                Integer int1 = role1.indexOf("管理员");
                if (UserUtils.getUser().getName().equals("系统管理员") || int1 == -1) {
                    if (!user.isAdmin()) {
                        paramMap.put("createBy", user.getId());
                    }
                    Page<Map<String, Object>> page = flowService.getPageFlowInfo(new Page<FlowData>(request, response), paramMap);
                    List<Map<String, Object>> flowInfo = page.getList();
                    flowParam.setDatas(new HashMap<String, Object>());
                    flowParam.getDatas().put("flowInfo", flowInfo);
                    flowParam.getDatas().put("page", page);
                } else {
                    String companyId2 = user.getCompany().getId();
//                    List<User> list = systemService.findUserByCompanyId(companyId2);
                    Page<Map<String, Object>> page = null;
                    List<Map<String, Object>> flowInfo = new ArrayList<>();
                    if (!UserUtils.getUser().isAdmin() && !role1.endsWith("管理员")) {
                        paramMap.put("createBy", UserUtils.getUser().getId());
                        page = flowService.getPageFlowInfo(new Page<FlowData>(request, response), paramMap);
                        List<Map<String, Object>> flowInfo1 = page.getList();
                        flowInfo.addAll(flowInfo1);
                    } else {
                        page = flowService.getPageFlowInfo(new Page<FlowData>(request, response), paramMap);
                        if (page.getList() != null) {
                            for (int i = 0; i < page.getList().size(); i++) {
                                //拿到每条数据的createBy创建人
                                String person = page.getList().get(i).get("create_by").toString();
                                User user11 = userDao.findByCompanyId(companyId2, person);
                                if (user11 != null) {
                                    flowInfo.add(page.getList().get(i));
                                }
                            }
                        }
                    }
                    flowParam.setDatas(new HashMap<String, Object>());
                    flowParam.getDatas().put("flowInfo", flowInfo);
                    flowParam.getDatas().put("page", page);
                }
                Component c;
                if(DeviceType.MOBILE.equals(userAgent.getOperatingSystem().getDeviceType())){
                    c = ComponentUtils.getComponent("myTouchFlow");
                }
                else{
                    c = ComponentUtils.getComponent("myFlow");
                }
                html = c.getContent().replace("$selfFlowHTML$", selfFlowHTML.toString())
                        .replace("$tbodyHTML$", tbodyHTML.toString())
                        .replace("$theadHTML$", theadHTML.toString());
            }
        }
        try {
            response.getWriter().print(FreemarkerUtils.process(html, toMap(flowParam)));
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 我发起的流程上拉加载
     * @param flowData
     * @param procDefId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "touchFlow")
    @ResponseBody
    public List<Map> touchFlow(FlowData flowData,@RequestParam(value="procDefId", required=false)String procDefId,@RequestParam(value="pageNo", required=false)int pageNo,@RequestParam(value="pageSize", required=false)int pageSize) {
        Page<FlowData> page=new Page();
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        String cate = null;
        String category="";
        List<Role> roles = roleDao.getByRoleName(UserUtils.getUser().getId());//获取当前人员的职位信息
        String companyId = UserUtils.getUser().getCompany().getId();//获取当前人员的单位
        User user1 = userDao.findUserByRoleName(new User());//获取集团管理员的机构id
        for (Role role : roles) {
            if (StringUtils.equalsIgnoreCase(companyId, "1")) {
                category = "";
            } else if (StringUtils.equalsIgnoreCase(role.getName(), "集团管理员") || StringUtils.equalsIgnoreCase(UserUtils.getUser().getCompany().getId(), user1.getCompanyId())
                    || StringUtils.equalsIgnoreCase(role.getName(), "深圳管理员") || StringUtils.equalsIgnoreCase(UserUtils.getUser().getCompany().getId(), user1.getCompanyId())) {
                category = "1";
            } else {
                category = "2";
            }//根据人员职位获取栏目类型
        }
        if (StringUtils.isNotEmpty(category)) {
            cate = category;
        }
        List<Object[]> processList = ProcessDefUtils.processList(cate);//保存两个对象，流程定义和流程部署
        //默认选择第一个流程
        if (StringUtils.isBlank(procDefId) && processList.size() > 0) {
            ProcessDefinition process = (ProcessDefinition) processList.get(0)[0];
            procDefId = process.getId();//流程定义id
        }
        String formKey = actTaskService.getFormKey(procDefId, null);//由流程id获取流程节点KEY
        Page<Map<String, Object>> pageList=new Page<>();
        if (StringUtils.isNotBlank(formKey) && !"/404".equals(formKey)) {
            OaFormMaster form = oaFormMasterService.findByNo(formKey, null);//用表单主键获取表单样式
            Map<String, String> paramMap = new HashMap<>();
            if (form != null) {
                paramMap.put("tableName", form.getTableName());
            }
                paramMap.put("procDefId", procDefId);
                User user = UserUtils.getUser();
                String role1 = UserUtils.getRole().get(0).getName();
                Integer int1 = role1.indexOf("管理员");
                if (UserUtils.getUser().getName().equals("系统管理员") || int1 == -1) {
                    if (!user.isAdmin()) {
                        paramMap.put("createBy", user.getId());
                    }
                    pageList = flowService.getPageFlowInfo(page, paramMap);
                } else {
                    if (!UserUtils.getUser().isAdmin() && !role1.endsWith("管理员")) {
                        paramMap.put("createBy", UserUtils.getUser().getId());
                        pageList = flowService.getPageFlowInfo(page, paramMap);
                    } else {
                        pageList = flowService.getPageFlowInfo(page, paramMap);
                    }
            }
        }
        List<Map> list=new ArrayList<>();
        Map<String,String> dataMap=new HashMap<String,String>();
        List data = pageList.getList();
        if(data.size()>0){
            for(int i=0; i<data.size(); i++) {
                list.add(dataMap);
            }
        }
        return list;
    }
    /**
     * 删除流程信息
     *
     * @param tableName
     * @param id
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "deleteInfo")
    public String deleteInfo(String procInsId, String tableName, String id, RedirectAttributes redirectAttributes) {
        //删除流程实例，确保删除不彻底
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(procInsId).singleResult();
        if (pi == null) {
            historyService.deleteHistoricProcessInstance(procInsId);
        } else {
            runtimeService.deleteProcessInstance(procInsId, "");
        }
        oaPersonDefineTableService.deleteInfo(tableName, id);
        addMessage(redirectAttributes, "删除已发起流程成功");
        return "redirect:" + Global.getAdminPath() + "/oa/flow/myFlow?repage";
    }

    /**
     * 表单内存处理掉[...]
     *
     * @param oaFormMaster
     * @param view
     */
    private void initComponent(OaFormMaster oaFormMaster, String view, boolean init) {
        OaPersonDefineTable oaPersonDefineTable = this.oaPersonDefineTableService.findByTableName(oaFormMaster.getTableName(), null);
        List<OaPersonDefineTableColumn> oaPersonDefineTableColumns = this.oaPersonDefineTableService.findColumnListByTableId(oaPersonDefineTable.getId());
        String tableContent = oaFormMaster.getContent();
        for (OaPersonDefineTableColumn column : oaPersonDefineTableColumns) {
            if (column != null && !"".equals(column)) {
                String content = "";
                if ("flowForm".equals(view) && !"REMARK".equalsIgnoreCase(column.getColumnType())) {
                    Map<String, Object> columnMap = new HashMap<>();
                    columnMap.put("value", column.getControlTypeId());
                    columnMap.put("columnName", column.getColumnName());
                    if (ComponentUtils.chargeMoreData(column.getControlTypeId())) {
                        columnMap.put("optData", DictUtils.getDictList(column.getRemarks()));
                    }
                    content = ComponentUtils.initComponent(columnMap, init);
                    if ("text".equals(column.getControlTypeId()) || "number".equals(column.getControlTypeId()) || "textValue".equals(column.getControlTypeId())) {
                        content = content.replace("<input ", "<input style='width:98%;padding-left:0;padding-right:0;margin:0;border:0;'");
                    } else if ("textarea".equals(column.getControlTypeId())) {
                        content = content.replace("<textarea ", "<textarea style='width:99%;height:99%;padding:0;margin:0;border:0;'");
                    }
                } else if ("REMARK".equalsIgnoreCase(column.getColumnType())) {
                    content = "${" + column.getColumnName() + "}";

                } else {
                    content = "${" + column.getColumnName() + "}";
                }
                tableContent = tableContent.replace("[" + column.getColumnComment() + "]", content);
            }
        }
        oaFormMaster.setContent(tableContent);
    }

    /**
     * flowData中数据放入到Map
     *
     * @param flowData
     * @return
     */
    private Map<String, Object> toMap(FlowData flowData) {
        Map<String, Object> map = flowData.getDatas();
        if (map == null) {
            map = new HashMap<>();
        } else if (!"flowForm".equals(flowData.getShowType())) {
            OaPersonDefineTable oaPersonDefineTable = this.oaPersonDefineTableService.findByTableName(flowData.getTableName(), null);
            List<OaPersonDefineTableColumn> columns = this.oaPersonDefineTableService.findColumnListByTableId(oaPersonDefineTable.getId());
            if (columns.size() > 0) {
                if (map.get("flowInfo") != null) {
                    List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("flowInfo");
                    for (Map<String, Object> m : list) {
                        format(m, columns);
                    }
                } else {
                    format(map, columns);
                }
            }
        }
        map.put("tableName", flowData.getTableName());
        map.put("id", flowData.getId());
        map.put("formNo", flowData.getFormNo());
        map.put("ctx", Global.getAdminPath());
        Act act = flowData.getAct();
        if (act != null) {
            if (act.getTaskName() != null) {
                act.setTaskName(act.getTaskName());
            }
            map.put("act", act);
        }
        return map;
    }

    private String getInitJs(Map<String, Object> map, String tableName) {
        OaPersonDefineTable oaPersonDefineTable = this.oaPersonDefineTableService.findByTableName(tableName, null);
        List<OaPersonDefineTableColumn> columns = this.oaPersonDefineTableService.findColumnListByTableId(oaPersonDefineTable.getId());
        StringBuilder sb = new StringBuilder();
        if (columns != null && map != null && columns.size() > 0 && map.keySet().size() > 0) {
            for (OaPersonDefineTableColumn column : columns) {
                if (ComponentUtils.chargeMoreData(column.getControlTypeId()) && map.get(column.getColumnName()) != null) {
                    Component c = ComponentUtils.getComponent(column.getControlTypeId() + "Init");
                    sb.append(c.getContent().replace("${colName}", column.getColumnName()).replace("${colValue}", "${" + column.getColumnName() + "}"));
                }
            }
        }
        return sb.toString();
    }

    private void format(Map<String, Object> map, List<OaPersonDefineTableColumn> columns) {
        if (columns != null && map != null && columns.size() > 0 && map.keySet().size() > 0) {
            for (OaPersonDefineTableColumn column : columns) {
                if (ComponentUtils.chargeMoreData(column.getControlTypeId()) && map.get(column.getColumnName()) != null) {
                    map.put(column.getColumnName(), DictUtils.getDictLabels((String) map.get(column.getColumnName()), column.getRemarks(), ""));
                }
            }
        }
    }


    /**
     * 流程的统计查询
     *
     * @param procDefId 流程定义id
     * @param category  流程分类
     * @param name      名称
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param dept      部门
     * @param numberDay 天数
     * @param fh
     * @param arriveDay
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "query")
    public String query(String procDefId, String category, String name, String startDate, String endDate, String dept, String numberDay, String fh, String arriveDay, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        String html = "";
        String cate = null;
        FlowData flowParam = new FlowData();
        if (StringUtils.isNotEmpty(category)) {
            cate = category;
        }
        List<Object[]> processList = ProcessDefUtils.processList(cate);
        //默认选择第一个流程
        if (StringUtils.isBlank(procDefId)) {
            ProcessDefinition process = (ProcessDefinition) processList.get(0)[0];
            procDefId = process.getId();
        }
        //自定义流程HTML
        StringBuilder selfFlowHTML = new StringBuilder();
        for (Object[] objs : processList) {
            ProcessDefinition process = (ProcessDefinition) objs[0];
            selfFlowHTML.append("<option " + (procDefId.equals(process.getId()) ? "selected=\"selected\"" : "")
                    + " value=\"" + process.getId() + "\">" + process.getName() + "</option>");
        }

        String formKey = actTaskService.getFormKey(procDefId, null);
        if (StringUtils.isNotBlank(formKey) && !"/404".equals(formKey)) {
            OaFormMaster form = oaFormMasterService.findByNo(formKey, null);
            if (form != null) {
                String tableName = form.getTableName();
                flowParam.setTableName(tableName);
                flowParam.setFormNo(form.getFormNo());
                OaPersonDefineTable table = oaPersonDefineTableService.findByTableName(tableName, null);
                OaPersonDefineTableColumn param = new OaPersonDefineTableColumn();
                param.setIsShow("1");
                param.setTable(table);
                List<OaPersonDefineTableColumn> columns = oaPersonDefineTableService.findColumnList(param);
                StringBuilder theadHTML = new StringBuilder();
                StringBuilder tbodyHTML = new StringBuilder();
                for (OaPersonDefineTableColumn column : columns) {
                    theadHTML.append("<th>" + column.getColumnComment() + "</th>");
                    tbodyHTML.append("<td>${item." + column.getColumnName() + "}</td>");
                }

                Map<String, String> paramMap = new HashMap<>();
                paramMap.put("tableName", form.getTableName());
                paramMap.put("procDefId", procDefId);
                paramMap.put("name", name);
                paramMap.put("dept", dept);
                paramMap.put("numberDay", numberDay);
                paramMap.put("fh", fh);
                paramMap.put("arriveDay", arriveDay);
                paramMap.put("startDate", startDate);
                paramMap.put("endDate", endDate);
                Page<Map<String, Object>> page = flowService.getPageFlowInfo(new Page<FlowData>(request, response), paramMap);
                List<Map<String, Object>> flowInfo = page.getList();

                flowParam.setDatas(new HashMap<String, Object>());
                flowParam.getDatas().put("flowInfo", flowInfo);
                flowParam.getDatas().put("page", page);

                Component c = ComponentUtils.getComponent("query");
                html = c.getContent().replace("$selfFlowHTML$", selfFlowHTML.toString())
                        .replace("$tbodyHTML$", tbodyHTML.toString())
                        .replace("$theadHTML$", theadHTML.toString());
            }
        }
        try {
            response.getWriter().print(FreemarkerUtils.process(html, toMap(flowParam)));
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 人力资源管理者查看所有的流程信息
     *
     * @param procDefId
     * @param category
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "hrFlow")
    public String hrFlow(String procDefId, String category, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        String html = "";
        String cate = null;
        FlowData flowParam = new FlowData();
        if (StringUtils.isNotEmpty(category)) {
            cate = "1";
        }
        List<Object[]> processList = ProcessDefUtils.processList(cate);
        //默认选择第一个流程
        if (StringUtils.isBlank(procDefId) && processList.size() > 0) {
            ProcessDefinition process = (ProcessDefinition) processList.get(0)[0];
            procDefId = process.getId();
        }
        //自定义流程HTML
        StringBuilder selfFlowHTML = new StringBuilder();
        for (Object[] objs : processList) {
            ProcessDefinition process = (ProcessDefinition) objs[0];
            selfFlowHTML.append("<option " + (procDefId.equals(process.getId()) ? "selected=\"selected\"" : "")
                    + " value=\"" + process.getId() + "\">" + process.getName() + "</option>");
        }
        String formKey = actTaskService.getFormKey(procDefId, null);
        if (StringUtils.isNotBlank(formKey) && !"/404".equals(formKey)) {
            OaFormMaster form = oaFormMasterService.findByNo(formKey, null);
            if (form != null) {
                String tableName = form.getTableName();
                flowParam.setTableName(tableName);
                flowParam.setFormNo(form.getFormNo());
                OaPersonDefineTable table = oaPersonDefineTableService.findByTableName(tableName, null);
                OaPersonDefineTableColumn param = new OaPersonDefineTableColumn();
                param.setIsShow("1");
                param.setTable(table);
                List<OaPersonDefineTableColumn> columns = oaPersonDefineTableService.findColumnList(param);
                StringBuilder theadHTML = new StringBuilder();
                StringBuilder tbodyHTML = new StringBuilder();
                for (OaPersonDefineTableColumn column : columns) {
                    theadHTML.append("<th>" + column.getColumnComment() + "</th>");
                    tbodyHTML.append("<td>${item." + column.getColumnName() + "}</td>");
                }
                Map<String, String> paramMap = new HashMap<>();
                paramMap.put("tableName", form.getTableName());
                paramMap.put("procDefId", procDefId);
                User user = UserUtils.getUser();
                String role1 = UserUtils.getRole().get(0).getName();
                Integer int1 = role1.indexOf("管理员");
                if (UserUtils.getUser().getName().equals("系统管理员") || int1 == -1) {
                    if (!user.isAdmin()) {
                        paramMap.put("createBy", user.getId());
                    }
                    Page<Map<String, Object>> page = flowService.getPageFlowInfo(new Page<FlowData>(request, response), paramMap);
                    List<Map<String, Object>> flowInfo = page.getList();
                    flowParam.setDatas(new HashMap<String, Object>());
                    flowParam.getDatas().put("flowInfo", flowInfo);
                    flowParam.getDatas().put("page", page);
                } else {
                    String companyId2 = user.getCompany().getId();
                    Page<Map<String, Object>> page = null;
                    List<Map<String, Object>> flowInfo = new ArrayList<>();
                    if (!UserUtils.getUser().isAdmin() && !role1.endsWith("人事主管")) {
                        paramMap.put("createBy", UserUtils.getUser().getId());
                        page = flowService.getPageFlowInfo(new Page<FlowData>(request, response), paramMap);
                        List<Map<String, Object>> flowInfo1 = page.getList();
                        flowInfo.addAll(flowInfo1);
                    } else {
                        page = flowService.getPageFlowInfo(new Page<FlowData>(request, response), paramMap);
                        if (page.getList() != null) {
                            for (int i = 0; i < page.getList().size(); i++) {
                                //拿到每条数据的createBy创建人
                                String person = page.getList().get(i).get("create_by").toString();
                                User user11 = userDao.findByCompanyId(companyId2, person);
                                if (user11 != null) {
                                    flowInfo.add(page.getList().get(i));
                                }
                            }
                        }
                    }
                    flowParam.setDatas(new HashMap<String, Object>());
                    flowParam.getDatas().put("flowInfo", flowInfo);
                    flowParam.getDatas().put("page", page);
                }
                Component c = ComponentUtils.getComponent("hrFlow");
                html = c.getContent().replace("$selfFlowHTML$", selfFlowHTML.toString())
                        .replace("$tbodyHTML$", tbodyHTML.toString())
                        .replace("$theadHTML$", theadHTML.toString());
            }
        }
        try {
            response.getWriter().print(FreemarkerUtils.process(html, toMap(flowParam)));
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
